package com.wb.mas.ui.auth;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wb.mas.BR;
import com.wb.mas.BuildConfig;
import com.wb.mas.R;
import com.wb.mas.app.AppViewModelFactory;
import com.wb.mas.databinding.ActAuthExtraBinding;

import androidx.core.content.FileProvider;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.utils.ImageUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class AuthExtraAc extends BaseActivity<ActAuthExtraBinding, AuthExtraViewModel> {
    private Uri mImageUri;
    private static final String FILE_PROVIDER_AUTHORITY = BuildConfig.APPLICATION_ID+".fileprovider";
    public static final int TAKE_PHOTO_REQUEST_CODE1 = 101;
    private File imageFile;


    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.act_auth_extra;
    }

    @Override
    public int initVariableId() {
        return BR.authExtraViewModel;
    }

    @Override
    public AuthExtraViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(AuthExtraViewModel.class);
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.takePhotoEvent.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                requestCameraPermissions(TAKE_PHOTO_REQUEST_CODE1);
            }
        });
    }


    /**
     * 请求相机权限
     */
    private void requestCameraPermissions(final int takePhotoRequestCode) {
        //请求打开相机权限
        RxPermissions rxPermissions = new RxPermissions(AuthExtraAc.this);
        rxPermissions.request(Manifest.permission.CAMERA)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            doTakePhoto(takePhotoRequestCode);
                        } else {
                            ToastUtils.showShort("权限被拒绝");
                        }
                    }
                });
    }


    public void doTakePhoto(int requestCode) {
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//打开相机的Intent
        if (takePhotoIntent.resolveActivity(getPackageManager()) != null) {//这句作用是如果没有相机则该应用不会闪退，要是不加这句则当系统没有相机应用的时候该应用会闪退
            //创建用来保存照片的文件
            imageFile = createImageFile();
            if (imageFile != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    /*7.0以上要通过FileProvider将File转化为Uri*/
                    mImageUri = FileProvider.getUriForFile(this, FILE_PROVIDER_AUTHORITY, imageFile);
                } else {
                    /*7.0以下则直接使用Uri的fromFile方法将File转化为Uri*/
                    mImageUri = Uri.fromFile(imageFile);
                }
                takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);//将用于输出的文件Uri传递给相机
                startActivityForResult(takePhotoIntent, requestCode);//打开相机
            }
        }
    }

    /**
     * 创建用来存储图片的文件，以时间来命名就不会产生命名冲突
     *
     * @return 创建的图片文件
     */
    private File createImageFile() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File imageFile = null;
        try {
            imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageFile;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if ((requestCode == TAKE_PHOTO_REQUEST_CODE1) && resultCode == RESULT_OK) {
            /*如果拍照成功，将Uri用BitmapFactory的decodeStream方法转为Bitmap*/


            showDialog();


            ImageUtils.compressWithRx(imageFile.getAbsolutePath(), new Consumer() {
                @Override
                public void accept(Object o) throws Exception {
                    dismissDialog();
                    if (o instanceof File) {

                        viewModel.setImgPathToView(mImageUri, (File) o);
                    }

                }
            });


        }
    }
}
